package com.spzx.cart.service.impl;

import com.spzx.cart.api.domain.CartInfo;
import com.spzx.cart.service.ICartService;
import com.spzx.common.core.constant.SecurityConstants;
import com.spzx.common.core.context.SecurityContextHolder;
import com.spzx.common.core.domain.R;
import com.spzx.product.api.RemoteProductService;
import com.spzx.product.domain.ProductSku;
import com.spzx.product.domain.SkuPrice;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class ICartServiceImpl implements ICartService {


    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    RemoteProductService remoteProductService;

    private String getCartKey(Long userId) {
        //定义key user:userId:cart
        return "user:cart:" + userId;
    }

    @Override
    public void addToCart(Long skuId, Integer skuNum) {

        Long userId = SecurityContextHolder.getUserId();

        String cartKey = getCartKey(userId);

        // 查询购物车信息，判断是否新增或者修改
        CartInfo cartInfo = (CartInfo)redisTemplate.opsForHash().get(cartKey,skuId+"");

        if(null!=cartInfo){
            // 缓存中有信息，修改购物车信息
            cartInfo.setSkuNum(cartInfo.getSkuNum()+skuNum);
            redisTemplate.opsForHash().put(cartKey,skuId+"",cartInfo);
        }else {

            // 缓存中没有信息，新增购物车信息,远程调用product接口根据skuId查询商品信息
            R<ProductSku> productSkuR = remoteProductService.getProductSku(skuId, "inner");
            ProductSku sku = productSkuR.getData();
            cartInfo = new CartInfo();
            cartInfo.setCartPrice(sku.getSalePrice());
            cartInfo.setSkuPrice(sku.getSalePrice());
            cartInfo.setIsChecked(1);
            cartInfo.setThumbImg(sku.getThumbImg());
            cartInfo.setSkuName(sku.getSkuName());
            cartInfo.setSkuId(skuId);
            cartInfo.setUserId(userId);
            cartInfo.setSkuNum(skuNum);

            // 实时价格信息更新问题
            SkuPrice skuPrice = remoteProductService.getSkuPrice(skuId, "inner").getData();
            cartInfo.setCartPrice(skuPrice.getSalePrice());
            cartInfo.setCartPrice(skuPrice.getSalePrice());

            // 保存购物车信息
            redisTemplate.opsForHash().put(cartKey,skuId+"",cartInfo);
        }

    }

    @Override
    public List<CartInfo> cartList() {
        Long userId = SecurityContextHolder.getUserId();
        String cartKey = getCartKey(userId);
        // 查询缓存
        BoundHashOperations<String,String,CartInfo> boundHashOperations = redisTemplate.boundHashOps(cartKey);
        List<CartInfo> cartInfoList = boundHashOperations.values();

        // 更新实时价格,调用多次，查询多次，更新多次
//        for (CartInfo cartInfo : cartInfoList) {
//            Long skuId = cartInfo.getSkuId();
//            R<ProductSku> skuR = remoteProductService.getProductSku(skuId, "inner");
//            ProductSku sku = skuR.getData();
//            BigDecimal salePrice = sku.getSalePrice();
//            cartInfo.setSkuPrice(salePrice);
//            boundHashOperations.put(sku.getId()+"",cartInfo);
//        }

        // 更新实时价格,调用一次，查询一次，更新一次
        List<Long> skuIds = new ArrayList<>();
        skuIds = cartInfoList.stream().map(cartInfo -> {
            return cartInfo.getSkuId();
        }).collect(Collectors.toList());
        R<List<SkuPrice>> pricesR = remoteProductService.getSkuPriceList(skuIds, SecurityConstants.INNER);
        List<SkuPrice> prices = pricesR.getData();
//        for (CartInfo cartInfo : cartInfoList) {
//            for (SkuPrice price : prices) {
//                if(price.getSkuId()==cartInfo.getSkuId()){
//                    cartInfo.setSkuPrice(price.getSalePrice());
//                }
//            }
//        }
        Map<Long,BigDecimal> map = prices.stream().collect(Collectors.toMap(SkuPrice::getSkuId,SkuPrice::getSalePrice));
        for (CartInfo cartInfo : cartInfoList) {
            cartInfo.setSkuPrice(map.get(cartInfo.getSkuId()));
        }

        return cartInfoList;
    }

    @Override
    public void checkCart(Long skuId, Integer status) {
        Long userId = SecurityContextHolder.getUserId();
        String cartKey = getCartKey(userId);
        BoundHashOperations<String,String,CartInfo> boundHashOperations = redisTemplate.boundHashOps(cartKey);
        CartInfo cartInfo = boundHashOperations.get(skuId + "");
        cartInfo.setIsChecked(status);
        boundHashOperations.put(skuId+"",cartInfo);
    }

    @Override
    public void deleteCart(Long skuId) {
        Long userId = SecurityContextHolder.getUserId();
        String cartKey = getCartKey(userId);
        BoundHashOperations<String,String,CartInfo> boundHashOperations = redisTemplate.boundHashOps(cartKey);
        boundHashOperations.delete(skuId+"");

    }

    @Override
    public int updateCartPrice() {
        Long userId = SecurityContextHolder.getUserId();
        String cartKey = getCartKey(userId);
        // 查询缓存
        BoundHashOperations<String,String,CartInfo> boundHashOperations = redisTemplate.boundHashOps(cartKey);
        List<CartInfo> cartInfoList = boundHashOperations.values();

        // 查询数据库中的价格
        List<Long> skuIds = cartInfoList.stream().map(cartInfo -> {
            return cartInfo.getSkuId();
        }).collect(Collectors.toList());
        List<SkuPrice> skuPriceList = remoteProductService.getSkuPriceList(skuIds,"inner").getData();
        // 怎么更新？
        Map<Long, BigDecimal> map = skuPriceList.stream().collect(Collectors.toMap(SkuPrice::getSkuId, SkuPrice::getSalePrice));
        for (CartInfo cartInfo : cartInfoList) {
            cartInfo.setSkuPrice(map.get(cartInfo.getSkuId()));
        }
        return 0;
    }

    @Override
    public int removeCheckedCart() {
        Long userId = SecurityContextHolder.getUserId();
        String cartKey = getCartKey(userId);
        // 查询缓存
        BoundHashOperations<String,String,CartInfo> boundHashOperations = redisTemplate.boundHashOps(cartKey);
        List<CartInfo> cartInfoList = boundHashOperations.values();
        for (CartInfo cartInfo : cartInfoList) {
            if (cartInfo.getIsChecked() == 1){
                boundHashOperations.delete(cartInfo.getSkuId() + "");
            }

        }

        return 0;
    }


}
